import { app, shell, BrowserWindow, ipcMain, Tray, nativeImage, Menu, screen, dialog } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../build/icon.icns?asset'
import { setAutoLaunch, isAutoLaunch } from '../preload/scripts/common'
import { hasBattery } from '../preload/scripts/battery'

app.requestSingleInstanceLock()

if (!app.hasSingleInstanceLock()) {
  app.quit()
}

// 隐藏dock中的图标,同时隐藏了菜单栏
if (process.platform === 'darwin') {
  app.dock.hide()
}

let mainWindow = null
let tray = null
let winWidth = 320
let y = 100, x = 0

function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: winWidth,
    height: 220,
    x: x,
    y: y,
    show: false,
    autoHideMenuBar: true,
    useContentSize: true,
    frame: false,
    transparent: true,
    titleBarStyle: 'hidden',
    resizable: false,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
      // devTools: false
    }
  })

  // mainWindow.webContents.openDevTools({ mode: 'detach' })

  mainWindow.setMenu(null)
  Menu.setApplicationMenu(null)

  // hide traffic lights
  if (process.platform === 'darwin') {
    mainWindow.setWindowButtonVisibility(false)
  }

  // window on the top
  mainWindow.setAlwaysOnTop(true, 'screen-saver')

  // mainWindow.on('ready-to-show', () => {
  //   mainWindow.show()
  // })

  // minimize window
  ipcMain.on('winMini', () => {
    // mainWindow.minimize()
    mainWindow.hide()
  })

  ipcMain.on('showWin', () => {
    if (!mainWindow.isVisible()) {
      mainWindow.show()
    }
  })

  // change window height
  ipcMain.on('winHtChange', (_, winHt) => {
    const bounds = mainWindow.getBounds()
    bounds.height = winHt
    mainWindow.setBounds(bounds, true)
  })

  // 禁止用户手动最大化窗口
  mainWindow.setMaximizable(false)
  // 禁止用户调节窗口大小
  mainWindow.setResizable(false)

  // mainWindow.on('closed', () => {
  //   mainWindow = null
  // })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // 禁止某些快捷键：打开调试面板ctrl+shift+i；刷新ctrl+r
  mainWindow.webContents.on('before-input-event', (e, input) => {
    // console.log(input)
    if (
      (input.control && input.shift && input.key.toLowerCase() === 'i') ||
      (input.control && input.key.toLowerCase() === 'r') ||
      input.key.toLowerCase() === 'f12'
    ) {
      e.preventDefault()
    }
  })

  // 托盘菜单
  tray = new Tray(
    nativeImage.createFromPath(
      process.platform === 'win32'
        ? join(__dirname, '../../build/icon.ico')
        : join(__dirname, '../../build/icon.png')
    )
  )
  // const ctxMenu = Menu.buildFromTemplate([
  //   { label: 'Open', type: 'radio' },
  //   { label: 'Exit', type: 'radio' }
  // ])
  tray.setToolTip('Stats Me')
  // tray.setContextMenu(ctxMenu)

  // 切换窗口显示、隐藏
  tray.on('click', (event) => {
    if (mainWindow.isVisible()) {
      mainWindow.hide()
    } else {
      mainWindow.show()
    }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  hasBattery().then(data => {
    if (!data) {
      winWidth = 300
    }

    const primaryScreen = screen.getPrimaryDisplay()
    const { width, height } = primaryScreen.workAreaSize
    x = width - winWidth - 100

    createWindow()
  })

  // Set app user model id for windows
  electronApp.setAppUserModelId('com.mete.statsme')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // close window
  ipcMain.on('winClose', () => {
    app.quit()
  })

  // 监听开机启动
  ipcMain.on('openAtLogin', (e, flag) => {
    if (process.arch === 'arm64' && process.platform === 'darwin') {
      app.setLoginItemSettings({
        openAtLogin: flag
      })
      mainWindow.webContents.send('showMsg', { suc: true, lastVal: !flag })
    } else {
      setAutoLaunch(flag, mainWindow.webContents)
    }
  })

  // 监听isAutoLaunch事件，以获取应用是否随系统启动
  ipcMain.on('isAutoLaunch', () => {
    isAutoLaunch(app.getName()).then((isAutoLaunch) => {
      // console.log(isAutoLaunch)
      mainWindow.webContents.send('isAutoLaunch', isAutoLaunch)
    })
  })

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 防止调试
process.on('uncaughtException', (error) => {
  process.exit(1)
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
